using System;
using UnityEngine;

namespace Combat
{
    public class Health : MonoBehaviour
    {
        public event Action HealthChanged;
        public event Action<Vector2> Hit;
        public event Action Died;
        public event Action Reborn;

        public bool IsDead => Hp <= 0;
        public bool HasFullHealth => Hp == maxHp;

        public int Hp
        {
            get => _hp;
            private set
            {
                if (value < 0)
                    value = 0;
                else if (value > maxHp)
                    value = maxHp;
                _hp = value;
            }
        }

        public float NormalizedHp => (float)Hp / maxHp;

        [SerializeField] private int maxHp = 10;

        private int _hp;


        private void Awake()
        {
            _hp = maxHp;
        }

        public void TakeDamage(int damage, Vector2 hitDirection)
        {
            if (IsDead)
            {
                return;
            }
            
            Hp -= damage;
            Hit?.Invoke(hitDirection);
            HealthChanged?.Invoke();

            if (Hp <= 0)
            {
                Died?.Invoke();
            }
        }

        public void Heal(int amount)
        {
            int oldHp = Hp;
            Hp += amount;
            HealthChanged?.Invoke();

            if (Hp > 0 && oldHp <= 0)
            {
                Reborn?.Invoke();
            }
        }

        public void Die()
        {
            if (IsDead)
            {
                return;
            }
            
            Hp = 0;
            Died?.Invoke();
        }
    }
}